import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import XSTYLE from 'xlsx-style'

export const excelExport = function(title) {
  // 设置当前日期
  let time = new Date()
  let year = time.getFullYear()
  let month = time.getMonth() + 1
  let day = time.getDate()
  let name = year + '' + month + '' + day
  let excleTitle = title + name
  var xlsxParam = { raw: true }
  let fix = document.querySelector('.el-table__fixed-right')
  let wb
  // if (fix) {
  //   //判断要导出的节点中是否有fixed的表格，如果有，转换excel时先将该dom移除，然后append回去
  //   wb = XLSX.utils.table_to_book(
  //     document.querySelector('#exportTable', xlsxParam).removeChild(fix)
  //   )
  //   document.querySelector('#exportTable').appendChild(fix)
  // } else {
  //   wb = XLSX.utils.table_to_book(
  //     document.querySelector('#exportTable', xlsxParam)
  //   )
  // }
  if (fix) {
    //判断要导出的节点中是否有fixed的表格，如果有，转换excel时先将该dom移除，然后append回去
    wb = XLSX.utils.table_to_sheet(
      document.querySelector('#exportTable', xlsxParam).removeChild(fix)
    )
    document.querySelector('#exportTable').appendChild(fix)
  } else {
    wb = XLSX.utils.table_to_sheet(
      document.querySelector('#exportTable', xlsxParam)
    )
  }
  for (var i = 0; i < 11; i++) {
    wb['!cols'][i] = { wpx: 130 }
  }
  for (const key in wb) {
    if (key.indexOf('!') === -1 && wb[key].v) {
      wb[key].s = {
        font: {
          //字体设置
          sz: 13,
          bold: false,
          color: {
            rgb: '000000' //十六进制，不带#
          }
        },
        alignment: {
          //文字居中
          horizontal: 'center',
          vertical: 'center',
          wrap_text: true
        },
        border: {
          // 设置边框
          top: { style: 'thin' },
          bottom: { style: 'thin' },
          left: { style: 'thin' },
          right: { style: 'thin' }
        }
      }
    }
  }
  //var data = addRangeBorder(wb) //处理数据
  var sheetData = sheet2blob(wb, title)
  openDownloadDialog(sheetData, excleTitle + '.xlsx')
}
function addRangeBorder(data) {
  let arr = [
    'A',
    'B',
    'C',
    'D',
    'E',
    'F',
    'G',
    'H',
    'I',
    'J',
    'K',
    'L',
    'M',
    'N',
    'O',
    'P',
    'Q',
    'R',
    'S',
    'T',
    'U',
    'V',
    'W',
    'X',
    'Y',
    'Z'
  ]
  data['h1'] = 5
  // data.forEach(item => {
  //   let startColNumber = Number(item.s.r),
  //     endColNumber = Number(item.e.r)
  //   let startRowNumber = Number(item.s.c),
  //     endRowNumber = Number(item.e.c)
  //   const test = ws[arr[startRowNumber] + (startColNumber + 1)]
  //   for (let col = startColNumber; col <= endColNumber; col++) {
  //     for (let row = startRowNumber; row <= endRowNumber; row++) {
  //       ws[arr[row] + (col + 1)] = test
  //     }
  //   }
  // })
  return data
  console.log(data)
}
function sheet2blob(sheet, title) {
  var sheetName = title || 'sheet1'
  var workbook = {
    SheetNames: [sheetName],
    Sheets: {}
  }
  workbook.Sheets[sheetName] = sheet // 生成excel的配置项
  var wopts = {
    bookType: 'xlsx', // 要生成的文件类型
    bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
    type: 'binary'
  }
  var wbout = XSTYLE.write(workbook, wopts)
  var blob = new Blob([s2ab(wbout)], {
    type: 'application/octet-stream'
  }) // 字符串转ArrayBuffer
  function s2ab(s) {
    var buf = new ArrayBuffer(s.length)
    var view = new Uint8Array(buf)
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
    return buf
  }
  return blob
}
function openDownloadDialog(url, saveName) {
  if (typeof url == 'object' && url instanceof Blob) {
    url = URL.createObjectURL(url) // 创建blob地址
  }
  var aLink = document.createElement('a')
  aLink.href = url
  aLink.download = saveName || '' // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
  var event
  if (window.MouseEvent) event = new MouseEvent('click')
  else {
    event = document.createEvent('MouseEvents')
    event.initMouseEvent(
      'click',
      true,
      false,
      window,
      0,
      0,
      0,
      0,
      0,
      false,
      false,
      false,
      false,
      0,
      null
    )
  }
  aLink.dispatchEvent(event)
}
